﻿///
//轨迹查询及播放

var hisPlayWin; //轨迹播放窗体
var hisPlayStore; //轨迹记录
var smHistory; //grid选择模式
var setHisPlayDateWin; //设置轨迹播放时间窗体
var setHisPlaySpeedWin; //设置轨迹播放速度窗体
var hisTabPanel; //轨迹播放及列表面板
var hisPlayGrid; //轨迹列表
var isPlaying = 0; //是否在播放轨迹 0 未播放 1正在播放
var hisPlayTotalCount = 0; //轨迹播放中记录数
var hisPlayingIndex = 0; //当前播放轨迹第几条
var hisPlayStartDate = ""; //开始时间
var hisPlayEndDate = ""; //结束时间

var speedSlider_minValue = 1;
var speedSlider_maxValue = 20;
var speedSlider_value = 5;
var hisPlaySpeed = speedSlider_value;
var taskHisPlay;
var t = 0; //0,不执行，1执行
var intervalStep = 1;
var isShowMarkeLabel = true;
//function isShowMarkeLabelH() {
//    isShowMarkeLabel = !isShowMarkeLabel;
//    if (isShowMarkeLabel) {
//        Ext.MessageBox.alert("提示", "开启展示时间标签");
//    } else {
//        Ext.MessageBox.alert("提示", "禁止展示时间标签");
//        
//    }
//}
function historyPlay() {
    if (hisPlayStartDate == "") {
        var myDate = new Date();
        hisPlayStartDate = new Date(myDate.getTime() - 1000 * 60 * 60 * 24).format('Y-m-d H:i:s');
        hisPlayEndDate = myDate.format('Y-m-d H:i:s');
    }

    taskHisPlay = {
        run: playTimer,
        interval: (hisPlaySpeed * 100)
    };

    if (hisPlayWin != null) {
        hisPlayWin.close();
    }

    if (curVID != 0) {
        var historyRecord = Ext.data.Record.create([
	            { name: 'Lng' },
	            { name: 'Lat' },
	            { name: 'Speed' },
	            { name: 'Direction' },
	            { name: 'GpsTime' },
	            { name: 'Status' },
	            { name: 'Location' },
	            { name: 'LngOffset' },
	            { name: 'LatOffset' }
	            ]);

        var connObj = new Ext.data.Connection({
            timeout: 180000,
            url: '../Json/JsonGetVehicleHistoryInfoList.ashx',
            method: 'GET'
        });

        hisPlayStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy(connObj),
            reader: new Ext.data.JsonReader({ root: 'data' }, historyRecord)
        });

        smHistory = new Ext.grid.RowSelectionModel({
            singleSelect: true//只允许单选
        });

        hisPlayGrid = new Ext.grid.GridPanel({
            columns: [new Ext.grid.RowNumberer({
                header: "",
                //width　:　25,  
                renderer: function (value, metadata, record, rowIndex) {
                    return "<img src='../images/terminalstate.gif' title='定位有效'>";
                }
            }),
		            { header: "经度", dataIndex: "Lng" },
		            { header: "纬度", dataIndex: "Lat" },
		            { header: "速度", dataIndex: "Speed", width: 120 },
		            { header: "方向", dataIndex: "Direction", width: 130 },
		            { header: "定位时间", dataIndex: "GpsTime", width: 150 },
		            { header: "状态", dataIndex: "Status" },
		            { header: "位置", dataIndex: "Location", width: 150}],
            store: hisPlayStore,
            sm: smHistory
        });

        hisPlayGrid.addListener('cellclick', function (hisPlayGrid, rowIndex, columnIndex, e) {//单击，可以把celldblclick换成cellclick
            var dataStore = hisPlayStore;
            var myRcd = dataStore.getAt(rowIndex);
            var clickShowInfo = "<B><font color='#CC9900'>" + curLicensePlate + "</font></B><BR>" + "速度：" + myRcd.get('Speed') + "公里/小时<BR>" + "方向：" + myRcd.get('Direction') + "<br>" + "时间：" + myRcd.get('GpsTime') + "<BR>" + "经纬：" + myRcd.get('Lng') + "," + myRcd.get('Lat') + "<BR>";
            document.getElementById("iframeHistoryPlay").contentWindow.firstzoom();
            document.getElementById("iframeHistoryPlay").contentWindow.setterminalinfo(clickShowInfo);
            if ((myRcd.get('Lng') != 0) && (myRcd.get('Lat') != 0)) {
                document.getElementById("iframeHistoryPlay").contentWindow.setLatLng1(myRcd.get('Lng'), myRcd.get('Lat'), 0);
            }
            hisTabPanel.setActiveTab(0);
        });
        //
        hisTabPanel = new Ext.TabPanel({
            border: false, // already wrapped so don't add another border
            activeTab: 0, // second tab initially active
            region: 'center',
            tabPosition: 'bottom',
            items: [{
                html: "<IFRAME  border='0' id='iframeHistoryPlay' name='iframeHistoryPlay' src='../Services/history.html' frameBorder='0' width='100%' height='100%' scrolling='no'></IFRAME>",
                title: '地图区域',
                autoScroll: true
            }, {
                contentEl: 'trackplaydata',
                layout: 'fit',
                items: hisPlayGrid,
                title: '历史数据',
                autoScroll: true
            }]
        });

        hisTabPanel.on("tabchange", onTabChange);

        return new Ext.Panel({
            title: curLicensePlate + " - 轨迹回放",
            tbar: [
            { height: 35, icon: "../images/history/setting.png", text: '<span style="font-size:16px;">&nbsp设置时间段&nbsp&nbsp</span>', handler: setHisPlayDate },
            { height: 35, icon: "../images/history/play.png", text: '<span style="font-size:16px;">&nbsp播放&nbsp&nbsp</span>', handler: startHisPlay },
            { height: 35, icon: "../images/history/playfast.png", text: '<span style="font-size:16px;">&nbsp快速播放&nbsp&nbsp</span>', handler: showHisPlay },
            { height: 35, /*icon: "../images/history/pause.png",*/ text: '<span style="font-size:16px;">&nbsp暂停&nbsp&nbsp</span>', handler: stopHisPlay },
            { height: 35, /*icon: "../images/history/delete.png",*/ text: '<span style="font-size:16px;">清除播放轨迹&nbsp&nbsp</span>', handler: clearHisPlay },
            { height: 35, /*icon: "../images/history/timer.png",*/ text: '<span style="font-size:16px;">设置步骤点间隔&nbsp&nbsp</span>', handler: setStepInterval },
            { height: 35, /*icon: "../images/history/faster.png",*/text: '<span style="font-size:16px;">设置播放速度&nbsp&nbsp</span>', handler: setHisPlaySpeed },
            {
                xtype: "checkbox",
                checked: true,
                boxLabel: '<span style="font-size:16px;">时间标签&nbsp</span>',
                listeners: { "check": function (obj, ischecked) {
                    isShowMarkeLabel = ischecked;
                    if (isShowMarkeLabel) {
                        Ext.MessageBox.alert("提示", "开启展示时间标签");
                    } else {
                        Ext.MessageBox.alert("提示", "此后播放轨迹将不再显示时间标签");
                    }
                } 
                }
            }],

            layout: 'fit',
            //                contentEl: "historyPlayDIV",
            items: hisTabPanel,
            listeners: { "beforedestroy": function (obj) {
                hisPlayWin = null;
                hisPlayStore = null;
                smHistory = null;
                hisPlayGrid = null;
                hisTabPanel = null;
                isPlaying = 0;
                hisPlayTotalCount = 0;
                hisPlayingIndex = 0;
                Ext.TaskMgr.stopAll();
                t = 0;
                if (setHisPlayDateWin != null) {
                    setHisPlayDateWin.close();
                }
                if (setHisPlaySpeedWin != null) {
                    setHisPlaySpeedWin.close();
                }
                Ext.Msg.hide(); //隐藏进度条
            }
            }
            //                maximizable: false,
            //                maximized: true
        });
        //            hisPlayWin.show();
    }

    function onTabChange() {
        if ((hisPlayTotalCount != 0) && (hisPlayGrid != null) && (hisPlayStore != null) && (t == 1)) {
            smHistory.selectRow(hisPlayingIndex);
            var gv = hisPlayGrid.getView();
            gv.focusRow(hisPlayingIndex);
        }
        t = 1;
    }

    function startHisPlay() {
        if (document.getElementById("iframeHistoryPlay").contentWindow.getstartyoun() == 0) {
            Ext.Msg.alert('error', '地图正在加载中');
            return;
        }

        //hisTabPanel.setActiveTab(0);
        if (hisPlayingIndex == 0) {
            document.getElementById("iframeHistoryPlay").contentWindow.removeline();
            document.getElementById("iframeHistoryPlay").contentWindow.closeInfoWindow();
            Ext.TaskMgr.start(taskHisPlay); //启动定时获取数据任
        } else {
            document.getElementById("iframeHistoryPlay").contentWindow.closeInfoWindow();
            Ext.TaskMgr.start(taskHisPlay); //启动定时获取数据任
        }

    }

    function stopHisPlay() {
        isPlaying = 0;
        Ext.TaskMgr.stopAll(); //停止任务	
    }

    function clearHisPlay() {
        stopHisPlay();
        document.getElementById("iframeHistoryPlay").contentWindow.clearHisPlay();
        hisPlayingIndex = 0;
    }

    function setHisPlaySpeed() {

        if (setHisPlaySpeedWin != null) {
            setHisPlaySpeedWin.close();
        }

        var speedSlider = new Ext.Slider({
            width: 270,
            value: speedSlider_value,
            minValue: speedSlider_minValue,
            maxValue: speedSlider_maxValue,
            plugins: new Ext.slider.Tip({
                getText: function (thumb) {
                    hisPlaySpeed = thumb.value;
                    return String.format('{0}秒播放一步', thumb.value / 10.0);

                }
            })
            //plugins: new Ext.slider.Tip()
        });
        //        speedSlider.setValue(speedSlider_maxValue - (hisPlaySpeed - speedSlider_minValue + 1) + 1);//之前侯睿娴的方法
        speedSlider.setValue(hisPlaySpeed);
        var setupspeedFormPanel = new Ext.FormPanel({
            frame: true,
            labelWidth: 60,
            items: [speedSlider],
            buttons: [{
                text: '确定',
                handler: function () {
                    //                    hisPlaySpeed = speedSlider_maxValue - (speedSlider.getValue() - speedSlider_minValue + 1) + 1;//之前侯睿娴的方法
                    if (setHisPlaySpeedWin != null) {
                        setHisPlaySpeedWin.close();
                    }
                    taskHisPlay = {
                        run: playTimer,
                        interval: (hisPlaySpeed * 100)
                    };
                    if (isPlaying == 1) {
                        Ext.TaskMgr.stopAll();
                        Ext.TaskMgr.start(taskHisPlay);
                    }
                }
            }]
        });

        setHisPlaySpeedWin = new Ext.Window({
            layout: 'fit',
            title: '设置回放速度',
            width: 300,
            height: 110,
            collapsible: true, //折叠按钮
            closable: true, //关闭按钮
            closeAction: 'close',
            border: false,
            items: [setupspeedFormPanel],
            listeners: { "beforedestroy": function (obj) {
                setHisPlaySpeedWin = null;
                setupspeedFormPanel = null;
                speedSlider = null;
            }
            }
        });
        setHisPlaySpeedWin.show();
    }

    function setHisPlayDate() {
        if (document.getElementById("iframeHistoryPlay").contentWindow.getstartyoun() == 0) {
            Ext.Msg.alert('error', '地图正在加载中');
            return;
        }
        if (isPlaying == 1) {
            Ext.Msg.alert('error', '轨迹回放中');
            return;
        }
        if (setHisPlayDateWin != null) {
            setHisPlayDateWin.close();
        }

        var ctlHisPlayStartDate = new Ext.ux.form.DateTimeField({
            fieldLabel: '开始',
            width: 180,
            format: 'Y/m/d',
            allowBlank: false
        });
        var ctlHisPlayEndDate = new Ext.ux.form.DateTimeField({
            fieldLabel: '结束',
            width: 180,
            format: 'Y/m/d',
            allowBlank: false
        });
        if (hisPlayStartDate != "") {
            ctlHisPlayStartDate.setValue(hisPlayStartDate);
        }
        if (hisPlayEndDate != "") {
            ctlHisPlayEndDate.setValue(hisPlayEndDate);
        }
        var setupdateFormPanel = new Ext.FormPanel({
            frame: true,
            monitorValid: true,
            labelWidth: 60,
            items: [ctlHisPlayStartDate, ctlHisPlayEndDate],
            buttons: [{
                text: '确定',
                formBind: true,
                handler: function () {
                    hisPlayStartDate = ctlHisPlayStartDate.getValue().format('Y-m-d H:i:s');
                    hisPlayEndDate = ctlHisPlayEndDate.getValue().format('Y-m-d H:i:s');

                    if (hisPlayEndDate > hisPlayStartDate) {
                        if (setHisPlayDateWin != null) {
                            setHisPlayDateWin.close();
                        }

                        if (curVID != 0) {
                            var progressBar = Ext.Msg.show({
                                title: "请稍等",
                                msg: "正在加载后台数据",
                                width: 300,
                                wait: true,
                                waitConfig: { interval: 100, duration: 100000, fn: function () {
                                    Ext.Msg.hide();
                                }
                                },
                                closable: true
                            }); //进度条

                            hisPlayStore.load({
                                params: { startDate: hisPlayStartDate, endDate: hisPlayEndDate, vid: curVID }, //参数
                                callback: function (records, options, success) {
                                    Ext.Msg.hide(); //隐藏进度条
                                    progressBar = null;
                                    if (/*(hisPlayWin != null) && */(hisPlayStore != null)) {
                                        if (success) {
                                            if (records.length != 0) {
                                                hisPlayTotalCount = records.length;
                                                hisPlayingIndex = 0;
                                                taskHisPlay = {
                                                    run: playTimer,
                                                    interval: (hisPlaySpeed * 100)
                                                };
                                                t = 0;
                                                //hisTabPanel.setActiveTab(1);
                                                //document.getElementById("iframeHistoryPlay").contentWindow.removeline();
                                            } else {
                                                Ext.Msg.alert('提示', '这个时间段无记录返回');
                                                setHisPlayDate();
                                            }
                                        } else {
                                            Ext.Msg.alert('提示', '查询失败');
                                        }
                                    }
                                }
                            });
                        }
                    }
                    else {
                        Ext.Msg.alert('提示', '结束时间必须大于起始时间!', function (btn, text) {
                        });
                        hisPlayStartDate = "";
                        hisPlayEndDate = "";
                    }
                }
            }]
        });


        setHisPlayDateWin = new Ext.Window({
            layout: 'fit',
            title: '设置日期',
            width: 300,
            height: 135,
            collapsible: true, //折叠按钮
            closable: true, //关闭按钮
            closeAction: 'close',
            border: false,
            items: [setupdateFormPanel],
            listeners: { "beforedestroy": function (obj) {
                setHisPlayDateWin = null;
                setupdateFormPanel = null;
                ctlHisPlayStartDate = null;
                ctlHisPlayEndDate = null;
            }
            }
        });
        setHisPlayDateWin.show();
    }
}

function setStepInterval() {
    var itemPanel = new Ext.Panel({
        labelAlign: 'top',
        frame: true,
        items: [{ xtype: "label", width: 50, text: '间隔步数：' }, { xtype: 'textfield', width: 100, id: "IntervalSettingLabel"}]
    });
    var window = new Ext.Window({
        title: '人员信息列表',
        layout: 'fit',       //弹出窗口内布局会充满整个窗口;
        width: 250,          //设置窗口大小;
        height: 120,
        items: itemPanel,         //默认会生成Ext.Panel类型的对象;并且随窗口大小改变而改变;
        buttons: [{
            text: '确定',
            handler: function () {
                //                    alert(Ext.getCmp("IntervalSettingLabel").getValue());
                if (Ext.getCmp("IntervalSettingLabel").getValue()) {
                    intervalStep = Ext.getCmp("IntervalSettingLabel").getValue();
                    if (intervalStep < 0 || intervalStep == 0) {
                        intervalStep = 1;
                    }
                }
                window.close();

            }
        }]
    });
    window.show();
}

function showHisPlay() {
    document.getElementById("iframeHistoryPlay").contentWindow.showTheWholeLine(hisPlayStore, hisPlayTotalCount,isShowMarkeLabel);
//    for (var i = 0; i < hisPlayTotalCount; i++) {
//        playTimer();
//    }
}

function playTimer() {
    var wdy = 0;
    var jdx = 0;
    var wdyOffset = 0;
    var jdxOffset = 0;
    var str1 = "";
    var str2 = "";

    if (document.getElementById("iframeHistoryPlay").contentWindow.getstartyoun() == 0) {
        isPlaying = 0;
        Ext.TaskMgr.stopAll();
        return;
    }

    if (hisPlayTotalCount == 0) {
        isPlaying = 0;
        Ext.TaskMgr.stopAll();
        return;
    }
    if ((hisPlayStore == null) /*|| (hisPlayWin == null)*/) {
        isPlaying = 0;
        Ext.TaskMgr.stopAll();
        return;
    }
    isPlaying = 1;

    var myRcd = hisPlayStore.getAt(hisPlayingIndex);
    if ((myRcd.get('Lng') != 0) && (myRcd.get('Lat') != 0)) {
        wdy = myRcd.get('Lat');
        jdx = myRcd.get('Lng');
        wdyOffset = myRcd.get('Lat');
        jdxOffset = myRcd.get('Lng');
    }

    var clickShowInfo = "<B><font color='#CC9900'>" + curLicensePlate + "</font></B><BR>" + "速度：" + myRcd.get('Speed') + "公里/小时<BR>" + "方向：" + myRcd.get('Direction') + "<br>" + "时间：" + myRcd.get('GpsTime') + "<BR>" + "经纬：" + myRcd.get('Lng') + "," + myRcd.get('Lat') + "<br>"; ;
    document.getElementById("iframeHistoryPlay").contentWindow.setterminalinfo(clickShowInfo);

    var iconName = myRcd.get('Direction');
    if (hisPlayingIndex == 0) {
        document.getElementById("iframeHistoryPlay").contentWindow.startMarker(jdxOffset, wdyOffset, "begin3.png");
        document.getElementById("iframeHistoryPlay").contentWindow.setCenter(jdxOffset, wdyOffset);
    }
    if (hisPlayingIndex == (hisPlayTotalCount - 1)) {
        document.getElementById("iframeHistoryPlay").contentWindow.startMarker(jdxOffset, wdyOffset, "end3.png");
    }
    document.getElementById("iframeHistoryPlay").contentWindow.createline(jdxOffset, wdyOffset);
    document.getElementById("iframeHistoryPlay").contentWindow.AddHistoryMarker(isShowMarkeLabel, hisPlayingIndex, jdxOffset, wdyOffset, myRcd.get('GpsTime'), myRcd.get('Location'), myRcd.get('Direction'));
    document.getElementById("iframeHistoryPlay").contentWindow.getMapExtents(jdx, wdy);

    hisPlayingIndex = hisPlayingIndex + 1 * intervalStep;
    if (hisPlayingIndex > hisPlayTotalCount - 1) {
        // document.getElementById("iframeHistoryPlay").contentWindow.getAddress(jdxOffset, wdyOffset);
        isPlaying = 0;
        hisPlayingIndex = 0;
        Ext.TaskMgr.stopAll();
    }
}

/**
* 判断点是否在矩形内
* @param {Point} point 点对象
* @param {Bounds} bounds 矩形边界对象
* @returns {Boolean} 点在矩形内返回true,否则返回false
*/
function isPointInRect(point, bounds) {
    //检查类型是否正确
    if (!(point instanceof BMap.Point) ||
        !(bounds instanceof BMap.Bounds)) {
        return false;
    }
    var sw = bounds.getSouthWest(); //西南脚点
    var ne = bounds.getNorthEast(); //东北脚点
    return (point.lng >= sw.lng && point.lng <= ne.lng && point.lat >= sw.lat && point.lat <= ne.lat);
}